'use strict';

const db = uniCloud.database();
const dbCmd = db.command

exports.main = async (event, context) => {
  //event为客户端上传的参数
  console.log('event : ', event)
  if (event.collection == null) {
    return "参数错误";
  }
  let whereCon = {}
  switch (event.collection) {
    case "devTools":
      whereCon.title = dbCmd.eq(event.title)
      break
    case "poetry":
      if (event.type)
        whereCon.type = dbCmd.eq(event.type)
      if (event.title)
        whereCon.title = dbCmd.eq(event.title)
      break
    case "oldbook":
      if (event.type)
        whereCon.type = dbCmd.eq(event.type)
      if (event.bookName)
        whereCon.bookName = dbCmd.eq(event.bookName)
      if (event.chapterName)
        whereCon.chapterName = dbCmd.eq(event.chapterName)
      break
    case "movie":
      if (event.top250)
        whereCon.id = dbCmd.gt(event.start)
      break
    case "product":
      if (event.type == 'remove') await removeOssImage(event.images)
      break
    default: //这里直接从客户端传入where条件
      if (event.whereCon)
        whereCon = event.whereCon
      break
  }
  if (event.like) {//如果有查询like的条件，自动拆解里面的keys和value重新组成查询条件
    //参考：正则查询：https://uniapp.dcloud.net.cn/uniCloud/cf-database?id=regexp
    //参考：多条件查询：https://uniapp.dcloud.net.cn/uniCloud/cf-database?id=查询·逻辑操作符
    let likes = []
    let {keys, value} = event.like
    const query = value.trim()
    const queryRe = new RegExp(query, 'i')//正则查询
    keys.forEach(item => {//对keys的每一项进行正则查询
      likes.push({[item]: queryRe})
    })
    whereCon = dbCmd.or(likes)//重新赋值查询条件
    console.log("whereCon------", whereCon)
  }
  switch (event.type) {
    case "add":
      return addCollectionData(event.collection, event.add);
      break
    case "update":
      return updateCollectionData(event.collection, event.docId, event.update);
      break
    case "update-push":
      return updatePushCollectionData(event.collection, event.docId, event.updateKey, event.updateValue);
      break
    case "doc":
      return getCollectionDoc(event.collection, event.docId)
      break
    case "limit":
      return getCollectionDataLimit(event.collection, whereCon)
    case "remove":
      return removeDocData(event.collection, event.docId)
    default:
      return getCollectionData(event.collection, whereCon);
      break
  }
};

// 更新数据表里面的集合 参考：https://uniapp.dcloud.net.cn/uniCloud/cf-database?id=更新·数组操作符
async function updatePushCollectionData(collection, docId, updateKey, updateValue) {
  let updateObj = {}
  updateObj[updateKey] = dbCmd.push(updateValue)
  return new Promise((resolve, reject) => {
    db.collection(collection).doc(docId).update(updateObj).then(res => {
      resolve(res); //成功返回数据
    }).catch(msg => {
      reject(msg); //失败返回数据
    })
  })
}

// 更新数据库数据
async function updateCollectionData(collection, docId, updateData) {
  return new Promise((resolve, reject) => {
    db.collection(collection).doc(docId).update(updateData).then(res => {
      resolve(res); //成功返回数据
    }).catch(msg => {
      reject(msg); //失败返回数据
    })
  })
}

// 添加数据库数据
async function addCollectionData(collection, addData) {
  return new Promise((resolve, reject) => {
    db.collection(collection).add(addData).then(res => {
      resolve(res); //成功返回数据
    }).catch(msg => {
      reject(msg); //失败返回数据
    })
  })
}

// 查询数据库数据
async function getCollectionData(collection, whereCon) {
  console.log("whereCon", whereCon)
  return new Promise((resolve, reject) => {
    db.collection(collection).where(whereCon).get().then(res => {
      resolve(res); //成功返回数据
    }).catch(msg => {
      reject(msg); //失败返回数据
    })
  })
}

async function getCollectionDataLimit(collection, whereCon, limit = 10) {
  return db.collection(collection).where(whereCon).orderBy("id", "asc").limit(limit).get()
}

// 查询数据库特定数据
async function getCollectionDoc(collection, docId) {
  return db.collection(collection).doc(docId).get()
}

// 删除数据库特定数据
async function removeDocData(collection, docId) {
  return db.collection(collection).doc(docId).remove()
}

//删除oss图片
async function removeOssImage(images) {
  for (let i = 0; i < images.length; i++) {
    let data = {action: 'alioss-delete', object: images[i]}
    let result = await uniCloud.callFunction({name: 'com-power', data})
    console.log("removeOssImage===", result)
  }
}
